/**
 * 
 */
package com.googlecode.eventio.examples.chat;

import java.lang.management.ManagementFactory;

import javax.management.ObjectName;

import com.googlecode.eventio.EventDispatcherService;
import com.googlecode.eventio.Eventio;
import com.googlecode.eventio.Reaction;
import com.googlecode.eventio.config.Config;
import com.googlecode.eventio.config.Configuration;
import com.googlecode.eventio.jmx.StatisticsService;
import com.googlecode.eventio.stat.StatisticsImpl;

/**
 * @author steph
 * 
 */
public class ChatService {

	private final EventDispatcherService eventDispatcher;

	private final StatisticsImpl statistics = new StatisticsImpl();

	public ChatService() {
		eventDispatcher = Eventio.newEventDispatcher(new Configuration() {

			@Override
			public void configure(Config config) {
				config.statistics(statistics);
			}
		});

		initJmx();
	}

	public void initJmx() {

		StatisticsService statisticsService = new StatisticsService(statistics);

		try {
			ManagementFactory.getPlatformMBeanServer().registerMBean(statisticsService,
					new ObjectName("test", "name", "tt"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void folow(final String userName, final String folowedUser) {
		eventDispatcher.on(folowedUser, new Reaction<String>() {

			@Override
			public void react(String message) {
				System.out.println("Hey, " + userName + " user " + folowedUser + " say " + message);
			}
		});
	}

	public void post(String userName, String message) {
		eventDispatcher.emit(userName, message);
	}

}
